package io.renren.common.pojo;

import io.renren.common.xss.SQLFilter;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;

/**
 * 查询参数
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-14 23:15
 */
public class Query implements Serializable {
	private static final long serialVersionUID = 1L;

	private static final String DEFAULT_SIDX = "id";
	private static final String DEFAULT_ORDER = "desc";

    /**
     * 当前页码
     */
    @ApiModelProperty("页码")
    @Getter
    @Setter
    private Integer page;

    /**
     * 每页条数
     */
    @ApiModelProperty("每页条数")
    @Getter
    @Setter
    private Integer limit;

    @ApiModelProperty("排序字段")
    @Getter
    private String sidx;

    @ApiModelProperty("排序方式，如：asc、desc")
    @Getter
    private String order;

    public void setSidx(String sidx) {
        if(StringUtils.isNotBlank(sidx)){
            this.sidx = SQLFilter.sqlInject(sidx);
        }
    }

    public void setOrder(String order) {
        if(StringUtils.isNotBlank(order)){
            this.order = SQLFilter.sqlInject(order);
        }
    }

    public Integer getOffset() {
        if(page != null && limit != null){
            return (page - 1) * limit;
        }
        return null;
    }

    public String getOrderBy(){
        checkOrder();
        return this.getSidx() + " " + this.getOrder();
    }

    private void checkOrder(){
        if(StringUtils.isBlank(this.getSidx())){
            this.setSidx(DEFAULT_SIDX);
            this.setOrder(DEFAULT_ORDER);
        }
    }
}
